var app = getApp()
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    billid: '', //行程单ID
    activeIndex: -1,
    startY: 0,
    itemHeight: 400, // 项目高度（单位：rpx）
    isDragging: false,
    longPressTimer: null,
    touchStartTime: 0,
    currentTranslate: 0,
    list: [],
    moveId: '',
    deleteBillidList: [],// 已删除的资源点billid
    addpointShow: false,//新增点位弹窗
    excludeIds: [], //已有的资源点id集合
  },
  handleTouchStart(e) {
    const { index } = e.currentTarget.dataset;
    const startY = e.touches[0].clientY; // 计算绝对位置

    // 清除旧定时器
    if (this.data.longPressTimer) clearTimeout(this.data.longPressTimer);

    this.setData({
      touchStartTime: Date.now(),
      startY: startY,
      activeIndex: -1,
      isDragging: false
    });

    // 设置新定时器
    this.data.longPressTimer = setTimeout(() => {
      this.setData({
        isDragging: true,
        startY: startY, // 重新记录拖拽开始位置
        activeIndex: index,
        currentTranslate: 0
      });
      // wx.vibrateShort(); // 震动反馈
    }, 700);
  },

  handleTouchMove(e) {
    const { isDragging, activeIndex, touchStartTime } = this.data;
    // 未达长按时间时允许滚动
    if (!isDragging) {
      if (Date.now() - touchStartTime < 700) {
        clearTimeout(this.data.longPressTimer);
        this.setData({ activeIndex: -1 });
      }
      return;
    }

    // 拖拽逻辑
    const currentY = e.touches[0].clientY; // 绝对位置
    const deltaY = currentY - this.data.startY;

    // 更新当前项位移
    this.setData({
      currentTranslate: deltaY,
      [`list[${activeIndex}].translateY`]: deltaY
    });

    // 计算交换位置
    const itemHeightPx = this.data.itemHeight * wx.getSystemInfoSync().windowWidth / 750;
    const threshold = itemHeightPx / 2;
    if (Math.abs(deltaY) > threshold) {
      const direction = deltaY > 0 ? 1 : -1;
      const targetIndex = activeIndex + direction;

      if (targetIndex >= 0 && targetIndex < this.data.list.length) {
        const list = [...this.data.list];
        [list[activeIndex], list[targetIndex]] = [list[targetIndex], list[activeIndex]];

        // 补偿计算保持手指跟随
        // const compensation = deltaY - direction * threshold;
        const compensation = deltaY - direction * (itemHeightPx + 5); // 5px缓冲
        list[targetIndex].translateY = compensation;

        this.setData({
          list: list,
          activeIndex: targetIndex,
          startY: currentY - compensation,
          currentTranslate: compensation
        });
      }
    }
  },

  handleTouchEnd() {
    clearTimeout(this.data.longPressTimer);
    if (!this.data.isDragging) return;
    this.compute();
  },
  //计算天数&&上午下午
  compute(e) {
    if (e && e.detail) {
      //已选中要添加的资源点
      let selectList = e.detail.selectList;
      if (selectList) {
        this.setData({
          list: this.data.list.concat(selectList)
        })
      }
    }
    // 平滑复位
    let list = this.data.list.map(item => ({ ...item, translateY: 0 }));
    let totalDays = 1; // 总天数（整数表示全天，小数部分表示半天）
    list.forEach(item => {
      const studyDays = Number(item.jyxxts); // 学习天数（0.5表示半天）
      const isHalfDay = studyDays % 1 !== 0; // 是否为半天课程
      const isFullDayAvailable = totalDays % 1 === 0; // 当前是否处于全天时段

      if (isFullDayAvailable) {
        // 情况1：当前处于全天时段
        item.rq = totalDays; // 安排到当前全天
        item.sjd = isHalfDay ? '上午' : '全天';
        totalDays += isHalfDay ? 0.5 : studyDays;
      } else {
        // 情况2：当前处于半天时段（下午）
        if (isHalfDay) {
          // 情况2.1：安排到当前半天的下午
          item.rq = Math.floor(totalDays);
          item.sjd = '下午';
          totalDays += 0.5; // 当前半天结束，进入下个全天
        } else {
          // 情况2.2：需要跨到下一个全天
          const nextFullDay = Math.ceil(totalDays);
          item.rq = nextFullDay;
          item.sjd = '全天';
          totalDays = nextFullDay + studyDays;
        }
      }
    });
    this.setData({
      list: list,
      activeIndex: -1,
      isDragging: false,
      currentTranslate: 0
    });
  },

  //跳转资源点
  addZyd() {
    let excludeIds = '';
    this.data.list.forEach(item => {
      !excludeIds ? excludeIds += item.zyd_pk : excludeIds += (',' + item.zyd_pk)
    })
    this.setData({
      addpointShow: true,
      excludeIds
    })
    // 获取子组件实例
    const child = this.selectComponent('#addpoint');
    // 调用子组件方法
    if (child) {
      child.init();
    }
  },
  //提交
  submit() {
    const _this = this;
    util.request('/itf/common/hongpei/travelorder/saveTravelOrderDetailList.json?type='+_this.data.type, {
      billid: _this.data.billid,
      type: _this.data.type,
      list: _this.data.list,
      deleteBillidList: _this.data.deleteBillidList
    }, "POST").then(res => {
      if (res.success) {
        util.showMsg({
          msg: "提交成功",
          icon: 'success',
          success: () => {
            wx.navigateBack();
          }
        });
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  choiceCard(e) {
    let id = e.currentTarget.id
    const query = wx.createSelectorQuery()
    query.select('#' + id).boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      console.log(res)
    })
    this.setData({
      startY: e.detail.y
    })
  },
  //删除资源点
  zydDelete(e) {
    const _this = this;
    const index = e.currentTarget.dataset.index;
    let { list, deleteBillidList } = this.data;
    wx.showModal({
      title: '提示',
      content: '是否确认删除资源点？',
      success(res) {
        if (res.confirm) {
          if (list[index].billid) {
            deleteBillidList.push(list[index].billid);
          }
          list.splice(index, 1)
          _this.setData({
            list,
            deleteBillidList
          })
          _this.compute();
        }
      }
    })
  },
  //前往资源点详情
  goZydDetail(e) {
    const zyd_pk = e.currentTarget.dataset.zyd_pk;
    wx.navigateTo({
      url: '/pages/pointDetails/pointDetails?billid=' + zyd_pk,
    })
  },
  //获取数据
  queryTravelOrderDetailList() {
    const _this = this;
    util.request('/itf/common/hongpei/travelorder/queryTravelOrderDetailList.json', {
      billid: _this.data.billid,
      type: _this.data.type
    }).then(res => {
      if (res.success) {
        _this.setData({
          list: res.data
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      billid: options.billid,
      type: options.type
    })
    this.queryTravelOrderDetailList();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})